package com.sunny.ynhz.widget;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.sunny.ynhz.R;
import com.sunny.ynhz.ui.MainActivity;
import com.sunny.ynhz.ui.base.AppBaseTranslationTitleBarActivity;
import com.sunny.ynhz.utils.MD5Utils;

/**
 * Created by luao on 2017/7/26.
 */

public class MyWebview extends WebView {
    private Context mContext;

    public MyWebview(Context context) {
        super(context);
        mContext = context;
        initSettings();
    }

    public MyWebview(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        initSettings();
    }

    public MyWebview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initSettings();
    }


    private void initSettings() {
        if (mContext instanceof Activity) {
            ((Activity) mContext).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        }

        try {
            ((AppBaseTranslationTitleBarActivity) mContext).setLeftImage(R.mipmap.close);
        } catch (Exception e) {

        }

        WebSettings webSettings = getSettings();
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);

        //支持缩放
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);//隐藏Zoom缩放按钮
        //关闭缓存
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //自适应屏幕
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setLoadWithOverviewMode(true);

//        this.setInitialScale(100);
        webSettings.setAllowFileAccess(true); // 允许访问文件
        //会导致缩放有问题
//        webSettings.setUseWideViewPort(true);
        webSettings.setPluginState(WebSettings.PluginState.ON);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //当有新连接时，使用当前的 WebView
                //调用拨号程序
                if (url.startsWith("mailto:") || url.startsWith("geo:") || url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    mContext.startActivity(intent);
                } else {
                    view.loadUrl(url);
                }
                return true;
            }
        });

    }


    private long firstTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        long secondTime = System.currentTimeMillis();
        if (keyCode == KeyEvent.KEYCODE_BACK && this.canGoBack()) {
            this.goBack();
            return true;
        } else {
            if (!(mContext instanceof MainActivity)) {
                ((Activity) mContext).finish();
            } else {
                if (secondTime - firstTime < 2000) {
                    System.exit(0);
                } else {
                    Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime = System.currentTimeMillis();
                }
                return true;
            }
        }
        return true;
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        Log.e("scale", "" + getScrollX() + "-------" + getScrollY());
    }

    @Override
    public void loadUrl(String url) {
        if (url.indexOf("?") != -1) {
            super.loadUrl(url + "&token=" + MD5Utils.string2MD5((System.currentTimeMillis() * 5 - 1799) + "") + "&tokentime=" + System.currentTimeMillis());
        } else {
            super.loadUrl(url + "?token=" + MD5Utils.string2MD5((System.currentTimeMillis() * 5 - 1799) + "") + "&tokentime=" + System.currentTimeMillis());
        }

    }
}
